﻿using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static Lhxzn.LangExtractor.AITranslator;
using static Lhxzn.LangExtractor.LngFileManager;
using static System.Net.Mime.MediaTypeNames;

#region 文件信息
/****************************************************************
*	公司名称：福建力和行智能科技有限公司
*   作    者：Jeff
*   CLR 版本：4.0.30319.42000
*   创建时间：1/10/2025 1:47:54 PM
*	用 户 名：zheqichen 
*   描述说明：
*
*   修改历史：
*		1）	修 改 人：
*			修改日期：
*			修改内容：			
*
*****************************************************************/
#endregion


namespace Lhxzn.LangExtractor
{
    /// <summary>
    /// 类    名:UCShowAIChat
    /// 描    述:用户AI问答控件
    /// 修改时间:1/10/2025 1:47:54 PM
    /// </summary>
    public partial class UCShowAIChat : UserControl
    {

        #region 成员变量

        #region private
        private AITranslator.ChatRecord m_selectedRecord { get; set; }


        #endregion


        #region protected


        #endregion


        #region public
        /// <summary>
        /// 选择的对话记录
        /// </summary>
        public AITranslator.ChatRecord SelectedRecord
        {
            get { return m_selectedRecord; } 
            set
            {
                if (m_selectedRecord != value)
                {
                    m_selectedRecord=value;
                    RefreshView();
                }
            }
        }

        #endregion

        #endregion


        #region 构造函数
        /// <summary>
        /// 函 数 名:构造函数
        /// 函数描述:默认构造函数
        /// 修改时间:1/10/2025 1:47:54 PM
        /// </summary>
        public UCShowAIChat()
        {
            InitializeComponent();
            UIInitialize();
            SetEvents();
        }


        #endregion

        #region 父类函数重载、接口实现

        #endregion

        #region 函数

        #region private
        /// <summary>
        /// ui初始化
        /// </summary>
        private void UIInitialize()
        {
            tsbtn_HideCmd.Checked = true;
        }

        /// <summary>
        /// 事件注册
        /// </summary>
        private void SetEvents()
        {
            tsbtn_Edit.Click += OnClickTsbtnEdit;
            tsbtn_Save.Click += OnClickTsbtnSave;
            tsbtn_HideCmd.Click += OnClickTsbtnHideCmd;
            tsbtn_ReGen.Click += OnClickTsbtnReGen;
            tsbtn_OutputFile.Click += OnClickTsbtnOutputFile;
            tsbtn_Copy.Click += OnClickTsbtnCopy;
            rtxt_user.TextChanged += OnUserRtxtTextChanged;
            rtxt_assistant.TextChanged += OnAIRtxtTextChanged;
            tsbtn_AIRemoveBlankLine.Click += OnClickAIRemoveBlankLine;
            tsbtn_UserRemoveBlankLine.Click += OnUserRemoveBlankLine;
            tsbtn_FindKeyDiff.Click += OnClickFindKeyDiff;
        }

        /// <summary>
        /// 找AI和用户文本里面翻译键不同的第一个行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickFindKeyDiff(object? sender, EventArgs e)
        {
            var userLines = rtxt_user_hide.Lines;
            var aiLines= rtxt_assistant.Lines;
            int diffLine = -1;
            for (int i=0;i<userLines.Length;i++)
            {
                if (i >= aiLines.Length)
                {
                    diffLine=i; 
                    break;
                }

                if (userLines[i].StartsWith("[")&&userLines[i].TrimEnd('\n','\r','\v').EndsWith("]")&& userLines[i].Equals(aiLines[i]))
                {
                    continue;
                }

                if(!userLines[i].Contains("=") || !aiLines[i].Contains("="))
                {
                    diffLine = i;
                    break;
                }

                var userKey= userLines[i].Split("=").FirstOrDefault();
                var aiKey = aiLines[i].Split('=').FirstOrDefault();

                if (!userKey.Equals(aiKey))
                {
                    diffLine=i;
                    break;
                }
            }

            HighlightLine(rtxt_user_hide, diffLine);
            HighlightLine(rtxt_assistant, diffLine);
        }

        /// <summary>
        /// 高亮行
        /// </summary>
        /// <param name="box"></param>
        /// <param name="lineNumber"></param>
        private void HighlightLine(RichTextBox box, int lineNumber)
        {
            box.SelectAll();
            box.SelectionBackColor = Color.White;
            box.SelectionLength = 0;
            if (lineNumber < 0|| lineNumber>=box.Lines.Length)
            {
                return;
            }
            int startIndex = 0;
            for (int i = 0; i < lineNumber; i++)
            {
                startIndex += box.Lines[i].Length+1;
            }

            if (lineNumber == box.Lines.Length - 1)
            {
                startIndex -= 1;
            }

            int length = box.Lines[lineNumber].Length;

            box.Select(startIndex, length);
            box.SelectionBackColor = Color.Yellow; 
            box.SelectionLength = 0;
            box.ScrollToCaret();
        }

        /// <summary>
        /// 用户去除空白行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnUserRemoveBlankLine(object? sender, EventArgs e)
        {
            RemoveBlankLines(rtxt_user);
        }

        /// <summary>
        /// AI去除空白行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickAIRemoveBlankLine(object? sender, EventArgs e)
        {
            RemoveBlankLines(rtxt_assistant);
        }

        /// <summary>
        /// 删除多余的空白行
        /// </summary>
        /// <param name="richTextBox"></param>
        public void RemoveBlankLines(RichTextBox richTextBox)
        {
            var nonEmptyLines = richTextBox.Lines.Where(line => !string.IsNullOrWhiteSpace(line));
            nonEmptyLines = nonEmptyLines.Select(line => line.TrimEnd().Replace("\v", "")); ;
            richTextBox.Text = string.Join("\n", nonEmptyLines);
            if (m_selectedRecord != null)
            {
                m_selectedRecord.Assistant.Content = richTextBox.Text;
            }
        }

        /// <summary>
        /// 复制AI的文本内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickTsbtnCopy(object? sender, EventArgs e)
        {
            Clipboard.SetText(rtxt_assistant.Text);
        }

        /// <summary>
        /// AI的内容改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnAIRtxtTextChanged(object? sender, EventArgs e)
        {
            tsl_AiLineCount.Text = "行数：" + rtxt_assistant.Lines.Length;
        }

        /// <summary>
        /// 用户文本内容改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnUserRtxtTextChanged(object? sender, EventArgs e)
        {
            if (rtxt_user.Lines.Length > 0)
            {
                string[] lines = new string[rtxt_user.Lines.Length - 1];
                Array.Copy(rtxt_user.Lines, 1, lines, 0, lines.Length);
                rtxt_user_hide.Lines = lines;
            }
            else
            {
                rtxt_user_hide.Text = "";
            }
            tsl_UserLineCount.Text = "行数：" + rtxt_user_hide.Lines.Length;
        }

        /// <summary>
        /// 点击输出文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickTsbtnOutputFile(object? sender, EventArgs e)
        {
            if (m_selectedRecord == null)
            {
                return;
            }
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = $"选择文件夹,存储文件{m_selectedRecord.Name}";
            if (folderBrowserDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string selectedFilePath = folderBrowserDialog.SelectedPath;
            string path= Path.Combine(selectedFilePath, m_selectedRecord.Name);
            File.WriteAllTextAsync(path, rtxt_assistant.Text);
        }

        /// <summary>
        /// 点击重新生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnClickTsbtnReGen(object? sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(rtxt_user.Text))
            {
                return;
            }
            var temptRecord = m_selectedRecord;
            temptRecord.Assistant.Content = "等待AI翻译中...";
            RefreshView();
            string command= rtxt_user.Lines[0];
            string text = rtxt_user_hide.Text;
            string compeleteResponse= await AnalyzeLargeTextAsync(command, text);
            temptRecord.Assistant.Content = compeleteResponse;
            RefreshView();
        }

        /// <summary>
        /// 点击隐藏命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickTsbtnHideCmd(object? sender, EventArgs e)
        {
            SetHideCmdEnalbe(!tsbtn_HideCmd.Checked);
        }

        /// <summary>
        /// 点击保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickTsbtnSave(object? sender, EventArgs e)
        {
            if (m_selectedRecord != null)
            {
                m_selectedRecord.User.Content = rtxt_user.Text;
            }
            SetEditEnabled(true);
        }

        /// <summary>
        /// 点击编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickTsbtnEdit(object? sender, EventArgs e)
        {
            if (m_selectedRecord != null)
            {
                rtxt_user.Text = m_selectedRecord.User.Content;
            }
            SetEditEnabled(false);
        }


        #endregion


        #region protected



        #endregion


        #region public
        /// <summary>
        /// 刷新界面
        /// </summary>
        public void RefreshView()
        {
            SetUserRtxtContent(SelectedRecord?.User?.Content);
            SetAssistantRtxtContent(SelectedRecord?.Assistant?.Content);
        }

        /// <summary>
        /// 设置用户的文本
        /// </summary>
        /// <param name="content"></param>
        public void SetUserRtxtContent(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                content = "";
            }
            content= TrimEndEnter(content);
            if (rtxt_user.InvokeRequired)
            {
                rtxt_user.BeginInvoke(new Action(() =>
                {
                    this.rtxt_user.Text = content;
                    SetHideCmdEnalbe(tsbtn_HideCmd.Checked);
                    tsl_UserLineCount.Text ="行数：" +rtxt_user_hide.Lines.Length;
                }
                ));
            }
            else
            {
                this.rtxt_user.Text = content;
                SetHideCmdEnalbe(tsbtn_HideCmd.Checked);
                tsl_UserLineCount.Text = "行数：" + rtxt_user_hide.Lines.Length;
            }
        }

        /// <summary>
        /// 设置AI的文本
        /// </summary>
        /// <param name="content"></param>
        public void SetAssistantRtxtContent(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                content = "";
            }
            content = TrimEndEnter(content);
            if (rtxt_assistant.InvokeRequired)
            {
                rtxt_assistant.BeginInvoke(new Action(() => { this.rtxt_assistant.Text = content;
                    tsl_AiLineCount.Text = "行数：" + rtxt_assistant.Lines.Length;
                }));

            }
            else
            {
                this.rtxt_assistant.Text = content;
                tsl_AiLineCount.Text = "行数：" + rtxt_assistant.Lines.Length;
            }
        }

        /// <summary>
        /// 去除每行结尾的回车
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public string TrimEndEnter(string content)
        {
            char[] trimChars = { '\r', '\n' };
            return content.TrimEnd(trimChars);
        }

        /// <summary>
        /// 编辑开关
        /// </summary>
        /// <param name="enalbed"></param>
        public void SetEditEnabled(bool enalbed)
        {
            rtxt_user.ReadOnly = enalbed;
            tsbtn_Edit.Enabled = rtxt_user.ReadOnly;
            tsbtn_Save.Enabled = !rtxt_user.ReadOnly;
        }

        /// <summary>
        /// 隐藏命令行开关
        /// </summary>
        /// <param name="enabled"></param>
        public void SetHideCmdEnalbe(bool enabled)
        {
            tsbtn_HideCmd.Checked = enabled;
            if (tsbtn_HideCmd.Checked)
            {
                rtxt_user.Visible = false;
                rtxt_user_hide.Visible = !rtxt_user.Visible;
                tsbtn_Edit.Enabled = false;
                tsbtn_Save.Enabled = false;
                if (rtxt_user.Lines.Length > 0)
                {
                    string[] lines = new string[rtxt_user.Lines.Length - 1];
                    Array.Copy(rtxt_user.Lines, 1, lines, 0, lines.Length);
                    rtxt_user_hide.Lines = lines;
                }
                else
                {
                    rtxt_user_hide.Text = "";
                }
            }
            else
            {
                rtxt_user_hide.Visible = false;
                rtxt_user.Visible = !rtxt_user_hide.Visible;
                SetEditEnabled(rtxt_user.ReadOnly);
            }
        }
        #endregion

        #endregion

    }
}
